package com.example.finger;

import android.content.Context;
import android.text.TextUtils;

import com.example.finger.bean.LockLog;
import com.example.finger.bean.PadLock;
import com.example.finger.bean.TaskSheet;
import com.example.finger.bean.TaskWithPadlock;
import com.example.finger.rules.FingerLib;
import com.lyxmaster.lib.util.DataConfig;
import com.lyxmaster.lib.util.DateUtils;
import com.lyxmaster.lib.xutils.DbManager;
import com.lyxmaster.lib.xutils.db.table.TableEntity;
import com.lyxmaster.lib.xutils.x;

import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by LYX on 2018/11/14.
 */

public class FingerHelper {
    public static String TASTDIR = "/sdcard/Gyt/";
    public static String TASKPATH = "idPASide.txt";
    public static String MANAFIGER = "manaFiger.txt";
    public static String TMEMPTASK = "TMEMPTASK";
    private static FingerHelper s = null;
    public static int openLockOp1Index;
    public static int openLockOp2ndex;
    public String DevId = "";
    public FingerLib m_szHost;
    public List<TaskSheet> taskSheetList = new ArrayList<>();
    public TaskWithPadlock taskWithPadlocks;
    public List<TaskSheet> taskSheetTempList = new ArrayList<>();
    public int ManageFIngerID = 900;
    public int CollectionId = 1000;
    public boolean bOpeningLock = false;
    private DbManager.DaoConfig daoConfig;
    public DbManager dbManager;

    public FingerHelper() {

    }
    //同步代码快的demo加锁，安全高效
    public static FingerHelper getInStance(){
        if(s==null)
            synchronized (FingerHelper.class) {
                if(s==null)
                    s = new FingerHelper();
            }

        return s;

    }

    public void initDevId(Context context){
        String temp = DataConfig.getImei(context);
        DevId = temp.substring(temp.length()-8, temp.length());
    }

    public void openLock(TaskSheet taskSheet,String lockNum) throws Exception {
        getSendData(taskSheet, "A2", lockNum);
    }

    public void closeLock(TaskSheet taskSheet,String lockNum) throws Exception {
        getSendData(taskSheet, "A1", lockNum);
    }

    public void changPwd(TaskSheet taskSheet,String lockNum) throws Exception {
        getSendData(taskSheet, "B2", lockNum);
    }

    private void getSendData(TaskSheet taskSheet, String order,String lockNum) throws Exception {
        String id = DataConfig.hexByteToHexString(lockNum.getBytes(Charset.forName("US-ASCII")));

        PadLock padLock = FingerHelper.getInStance().dbManager.selector(PadLock.class).where("id","=",lockNum).findFirst();

        String[] pds = padLock.getPassword().split(",");
        String pd = "112233112233";
        if(pds.length == 2){
            pd = pds[1]+pds[1];
        }

        if(order == "B2"){
            if(pds.length != 2){
                throw new Exception("新旧密码格式错误");
            }
            pd = pds[0]+pds[1];
        }

        String s = "19" + order + id + pd + DateUtils.getStringDate("yyMMddHHmmss") + "0000" + DataConfig.hexByteToHexString(FingerHelper.getInStance().DevId.getBytes(Charset.forName("US-ASCII")));
        byte[] data = DataConfig.hexStringToHexBytes(s);
        data[0] = (byte)(data.length + 1);
        byte[] crc = DataConfig.CRC_16(data, data.length, 0x6290);
        String strData = "FE" + DataConfig.hexByteToHexString(data) + DataConfig.hexByteToHexString(crc) + "FF";
        SerialPortUtil.getInstance().sendDataToSerialPort(DataConfig.hexStringToHexBytes(strData));

        if(taskSheet == null) return;
        LockLog lockLog = new LockLog();
        lockLog.tasknum = taskSheet.getTask().getNumber();
        lockLog.keynum = FingerHelper.getInStance().DevId;
        lockLog.time = DataConfig.getStringDate();
        lockLog.operator1 = taskSheet.getOp1Finger().get(openLockOp1Index).getNickname();
        lockLog.operator2 = taskSheet.getOp2FInger().get(openLockOp2ndex).getNickname();
        lockLog.locknum = lockNum;
        lockLog.administrator = "";
        lockLog.doornumber = "";
        lockLog.remark = "";
        if(TextUtils.equals(order, "A1")){
            lockLog.state = "0";    //关
        }else {
            lockLog.state = "1";    //开
        }
        FingerHelper.getInStance().dbManager.save(lockLog);
    }

    private void change(TaskSheet taskSheet, String order,String lockNum) throws Exception {
        String id = DataConfig.hexByteToHexString(lockNum.getBytes(Charset.forName("US-ASCII")));

        PadLock padLock = FingerHelper.getInStance().dbManager.selector(PadLock.class).where("id","=",lockNum).findFirst();

        String[] pds = padLock.getPassword().split(",");
        String pd = "112233112233";
        if(pds.length == 2){
            pd = pds[1]+pds[1];
        }

        String s = "19" + order + id + pd + DateUtils.getStringDate("yyMMddHHmmss") + "0000" + DataConfig.hexByteToHexString(FingerHelper.getInStance().DevId.getBytes(Charset.forName("US-ASCII")));
        byte[] data = DataConfig.hexStringToHexBytes(s);
        data[0] = (byte)(data.length + 1);
        byte[] crc = DataConfig.CRC_16(data, data.length, 0x6290);
        String strData = "FE" + DataConfig.hexByteToHexString(data) + DataConfig.hexByteToHexString(crc) + "FF";
        SerialPortUtil.getInstance().sendDataToSerialPort(DataConfig.hexStringToHexBytes(strData));
    }

    public void initDb(){
        DbManager.DaoConfig daoConfig = new DbManager.DaoConfig()
                .setDbName("my_db.db") //设置数据库名
                .setDbVersion(2) //设置数据库版本,每次启动应用时将会检查该版本号,
                // 发现数据库版本低于这里设置的值将进行数据库升级并触发DbUpgradeListener
                .setAllowTransaction(true) //设置是否开启事务,默认为false关闭事务
                .setTableCreateListener(new DbManager.TableCreateListener() {
                    @Override
                    public void onTableCreated(DbManager dbManager, TableEntity<?> tableEntity) {
                    }
                })
                .setDbOpenListener(new DbManager.DbOpenListener() {
                    @Override
                    public void onDbOpened(DbManager db) {
                        // 开启WAL, 对写入加速提升巨大
                        db.getDatabase().enableWriteAheadLogging();
                    }
                })
                // 设置数据库创建时的Listener
                .setDbUpgradeListener(new DbManager.DbUpgradeListener() {
                    @Override
                    public void onUpgrade(DbManager db, int oldVersion, int newVersion) {
                        // TODO: ...

                    }
                }); //设置数据库升级时的Listener,这里可以执行相关数据库表的相关修改,比如alter语句增加字段等

        dbManager = x.getDb(daoConfig);
    }
}
